"use client";
import { useRouter } from "next/navigation";
import React, { use, useState, useEffect } from "react";
import {
  Table,
  Button,
  Input,
  Form,
  message,
  DatePicker,
  Col,
  Row,
  Steps,
  Divider,
  Spin,
} from "antd";
import type { TableProps } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import Container from "@/components/Container";
import { query, remove } from "@/api/snapshot";
import { build, deploy, rewind, gitlog } from "@/api/operate";
import { Props, DataType } from "./type";
import getColumns from "./column";
import dayjs from "dayjs";

const { RangePicker } = DatePicker;
const timeFormat = "YYYY-MM-DD HH:mm:ss";

export default function Snapshot(props: Props) {
  const router = useRouter();
  const [form] = Form.useForm();
  const { gitId, projectId } = use(props.params);
  const [loading, setLoading] = useState(false);
  const [spinning, setSpinning] = React.useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [stepLoading, setStepLoading] = useState(false);
  const [tableList, setTableList] = useState<DataType[]>([]);
  const [currentStep, setCurrentStep] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const rowSelection: TableProps<DataType>["rowSelection"] = {
    type: "radio",
    selectedRowKeys,
    onChange: (key: React.Key[], rows: DataType[]) => {
      const { id, snapshot_status: status } = rows[0];
      const currentStep = status >= 2 ? 1 : status;
      setCurrentStep(currentStep + 1);
      setSelectedRowKeys([id]);
    },
  };

  const onPaginationChange = (current: number) => {
    setPagination({
      ...pagination,
      current: current,
    });
  };

  // 消息提示
  const messageTip = (type: "success" | "error", content: string) => {
    messageApi.open({
      type,
      content,
    });
  };

  // 返回
  const handleBack = () => {
    router.back();
  };

  // 构建项目
  const handleBuild = async () => {
    try {
      setStepLoading(true);
      const { data } = await gitlog(projectId);
      const curTime = dayjs().format(timeFormat);
      const gitItem = data.find((item: any) => item.hash === gitId);
      const res = await build(projectId, gitId, curTime, gitItem.message);
      if (res.state) {
        messageTip("success", "构建成功");
        handleQuery();
      } else {
        messageTip("error", res.message);
      }
    } finally {
      setStepLoading(false);
    }
  };

  // 部署项目
  const handleDeploy = async () => {
    try {
      setStepLoading(true);
      const snapshotId = selectedRowKeys[0];
      const curTime = dayjs().format(timeFormat);
      const res = await deploy(projectId, snapshotId, curTime);
      if (res.state) {
        messageTip("success", "部署成功");
        handleQuery();
      } else {
        messageTip("error", res.message);
      }
    } finally {
      setStepLoading(false);
    }
  };

  // 上线
  const handleRewind = async (id: number) => {
    setSpinning(true);
    const res = await rewind(projectId, id).finally(() => {
      setSpinning(false);
    });
    if (res.state) {
      messageTip("success", "上线成功");
      handleQuery();
    } else {
      messageTip("error", res.message);
    }
  };

  // 删除
  const handleDelete = async (id: number) => {
    await remove(id);
    getList(getQueryParams());
    messageTip("success", "删除成功");
  };

  // 获取查询参数
  const getQueryParams = () => {
    const { snapshot_description = "", snapshot_time } = form.getFieldsValue();
    const start_time = snapshot_time ? snapshot_time[0].format(timeFormat) : "";
    const end_time = snapshot_time ? snapshot_time[1].format(timeFormat) : "";
    return {
      page_index: pagination.current,
      page_size: pagination.pageSize,
      project_id: projectId,
      snapshot_description,
      start_time,
      end_time,
    };
  };

  // 查询
  const handleQuery = () => {
    getList(getQueryParams());
  };

  // 获取列表
  async function getList(params: any) {
    setLoading(true);
    const res = await query(params).finally(() => {
      setLoading(false);
    });
    if (res.state) {
      const { total, list } = res.data;
      setPagination({
        ...pagination,
        total,
      });
      setTableList(list);
    }
  }

  useEffect(handleQuery, []);

  useEffect(() => {
    const get = (status: number) => (status >= 2 ? 1 : status);
    const item = tableList.find((o) => o.git_commit_id == gitId) as DataType;
    const currentStep = item ? get(item.snapshot_status) : -1;
    const currentSelected = item ? [item.id] : [];
    setCurrentStep(currentStep + 1);
    setSelectedRowKeys(currentSelected);
  }, [tableList]);

  useEffect(handleQuery, [pagination.current]);

  return (
    <>
      {contextHolder}
      <Container>
        <Spin spinning={spinning} fullscreen />
        <Steps
          current={currentStep as number}
          items={[
            {
              title: "开始准备",
              icon: currentStep === 0 && stepLoading && <LoadingOutlined />,
              description: currentStep === 0 && (
                <Button
                  type="primary"
                  style={{ marginTop: 5 }}
                  disabled={stepLoading}
                  onClick={handleBuild}
                >
                  打包
                </Button>
              ),
            },
            {
              title: "打包完成",
              icon: currentStep === 1 && stepLoading && <LoadingOutlined />,
              description: currentStep === 1 && (
                <Button
                  type="primary"
                  style={{ marginTop: 5 }}
                  disabled={stepLoading}
                  onClick={handleDeploy}
                >
                  部署
                </Button>
              ),
            },
            {
              title: "部署完成",
            },
          ]}
        />
        <Divider />
        <Row style={{ margin: "20px 0" }}>
          <Col span={22}>
            <Form layout="inline" form={form}>
              <Form.Item name="snapshot_description" label="快照描述">
                <Input placeholder="请输入" allowClear />
              </Form.Item>
              <Form.Item name="snapshot_time" label="快照时间">
                <RangePicker showTime allowClear />
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={handleQuery}>
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Col>
          <Col span={2} style={{ textAlign: "right" }}>
            <Button
              color="green"
              variant="solid"
              type="primary"
              onClick={handleBack}
            >
              返回
            </Button>
          </Col>
        </Row>
        <Table<DataType>
          loading={loading}
          rowSelection={rowSelection}
          columns={getColumns(handleRewind, handleDelete)}
          pagination={{ ...pagination, onChange: onPaginationChange }}
          dataSource={tableList}
          tableLayout="auto"
          rowKey="id"
          scroll={{
            x: "80%",
            y: 284,
          }}
        />
      </Container>
    </>
  );
}
